/*================================================================*
        Copyright (C) 2021 All rights reserved www.hsby.link
      	�ļ����ƣ�test_socket_srv.cc
      	�� �� �ߣ���ɭ����
      	�������ڣ�2021/12/16
 *================================================================*/

#include "socket.h"
#include "util/util.h"
#include "iomanager.h"

void TestConnect() {
    // ��ʼ�������׽���
    hsby::Socket listen_sock(AF_INET, SOCK_STREAM, 0);
    listen_sock.Init();
    auto local_addr = hsby::Ipv4Address::Create("127.0.0.1", 10086);
    if (!listen_sock.Bind(local_addr)) {
        //HSBY_LOG_SYSTEM_DEBUG << HSBY_ERROR_EXP;
        return;
    }

    // ������������(�����������׽���)
    listen_sock.Listen();
    auto connected_sock = listen_sock.Accept();
    if (!connected_sock) {
        //HSBY_LOG_SYSTEM_DEBUG << HSBY_ERROR_EXP;
        return;
    }
    //HSBY_LOG_SYSTEM_DEBUG << "Connect success! " << HSBY_VARS_EXP(connected_sock->ToString());

    int recv_size = 0;
    do {
        // ����
        fd_set fdset;
        FD_ZERO(&fdset);
        FD_SET(connected_sock->GetSockfd(), &fdset);
        select(connected_sock->GetSockfd() + 1, &fdset, nullptr, nullptr, 0);
        std::string recv_buf;
        recv_size = connected_sock->Recv(recv_buf);
        //HSBY_LOG_SYSTEM_DEBUG << HSBY_VARS_EXP(recv_size, recv_buf);

        // ����
        int send_size = connected_sock->Send(recv_buf);
        HSBY_LOG_SYSTEM_DEBUG << HSBY_VARS_EXP(send_size);
    }while(recv_size != 0);
}

int main() {
    hsby::IoManager iom;
    iom.AddTask(TestConnect);
    return 0;
}
